<?php
namespace app\admin\model;
use think\Model;
use think\Db;
class Index extends Model
{
	/**
	 * 判断用户登录帐号密码
	 */
	public function checkLogin($username,$password){
		
		//查询用户表里记录
		$user=Db::name("user")->where(['username'=>$username,'status'=>0])->find();
		
		if(empty($user)){
			return json(['code'=>201,'msg'=>"用户名错误"]);exit;
		}

		if(md5($password.$user['salt'])!=$user['password']){		
			return json(['code'=>201,'msg'=>"密码错误"]); exit;
		}
				
		//更新登陆时间和登陆ip		
		$user['login_time'] =time();
		$user['login_ip'] =ip2long(request()->ip());		
		Db::name("user")->update($user);
		//记录登陆日志
		LoginLog::create(['user_id'=>$user['uid'],'login_time'=>time(),'login_ip'=>ip2long(request()->ip())]);
		//获取角色权限
		$role=Roles::get(['dataflag'=>1,'roleid'=>$user['roleid']]);
		
		//获取角色的菜单
		if($user['uid']==1){
			$user['privileges'] = Db::name('privileges')->where(['dataflag'=>1])->column('privilege_code');
			$user['menuids'] = Db::name('menus')->where('dataflag',1)->column('menuid');
		}else{
			$user['privileges'] = explode(",", $role['privileges']);
			$user['menuids'] = [];
			if(!empty($user['privileges'])){
				$menus=Db::name("menus")->alias("m")->join('__PRIVILEGES__ p','m.menuid=p.menuid and p.dataflag=1','inner')->where(['p.privilege_code'=>['in',$user['privileges']]])->field('m.menuid')->select();
				$menuids=[];
				if(!empty($menus)){
					foreach($meuns as $key => $v){
						$menuids[]=$v['menuid'];						
					}
					$user['menuids']=$menuids;
				}
			}
		}
		session("user",$user);
		return json(['code'=>200,'msg'=>$user]);
	}

}